package com.fg.cloud.system.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.shiro.CustomLoginToken;
import com.fg.cloud.manager.entry.system.SystemUserEntity;
import com.fg.cloud.manager.entry.system.vo.SystemUserVo;
import com.fg.cloud.manager.service.system.SystemUserService;

/**
 * Description:系统用户Controller
 * @author dingjiang
 * @date 2017年10月19日下午3:03:48
 */
@Controller
@RequestMapping("/systemUser")
public class SystemUserController extends BaseSystemController {

	@Autowired
    private SystemUserService systemUserService;
	
	@RequestMapping(value="/resetPsd", method=RequestMethod.GET)
	@ResponseBody
	public String resetPsd(HttpServletRequest request, HttpServletResponse response){
		return "resetPsd";
	}
	
	/**请求登录，验证用户
	 * @param userName password
	 * @return Object
	 * @throws Exception
	 */
	@RequestMapping(value="/systemLogin", method=RequestMethod.GET)
	@ResponseBody
	public String requestLogin(HttpServletRequest request, HttpServletResponse response, 
			String userName, String password) throws Exception {
		
		if (null == userName) {
			doResult(response, false, StatusCode.LACKVALUE, null, "用户名不能为空");
			return null;
		}
		if (null == password) {
			doResult(response, false, StatusCode.LACKVALUE, null, "密码不能为空");
			return null;
		}
		
		Subject subject = SecurityUtils.getSubject();
		
		CustomLoginToken token = new CustomLoginToken(userName, 
        		DigestUtils.md5Hex(password), UserType.SYSTEM);
        token.setRememberMe(true);
        
        System.out.println("token接收的数据："+token.getUsername()+"--"+token.getPassword().toString());

        try {
        	subject.login(token);
        } catch (ServiceException e) {
        	logger.error("登录状态校验失败，请重试", e);
            doResult(response, false, StatusCode.NORETRUNDATA, null, "登录状态校验失败，请重试");
            return null;
        } catch (UnknownAccountException e) {
        	logger.error("账号不存在", e);
            doResult(response, false, StatusCode.NORETRUNDATA, null, "用户名不存在");
            return null;
        } catch (DisabledAccountException e) {
        	logger.error("账号未启用", e);
            doResult(response, false, StatusCode.NORETRUNDATA, null, "账号未启用");
            return null;
        } catch (IncorrectCredentialsException e) {
        	logger.error("密码错误", e);
            doResult(response, false,StatusCode.NORETRUNDATA, null, "密码错误");
            return null;
        } catch (RuntimeException e) {
        	logger.error("未知错误,请联系管理员", e);
            doResult(response, false,StatusCode.NORETRUNDATA, null, "未知错误,请联系管理员");
            return null;
        }
		
		return "index";
	}
	
	 
	/**
	 * 用户退出登陆
	 * @param session
	 * @return Object
	 * @throws Exception 
	 */
	@RequestMapping(value="/logout" ,produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object logout() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		
		Session session = SecurityUtils.getSubject().getSession();
		String userName = session.getAttribute("userName").toString();
		System.out.println(userName+"：退出登陆...");
		 
		Subject subject = SecurityUtils.getSubject();//shiro销毁登录
		subject.logout();
		String result = "success";
		map.put("result", result);
		return  map;
	}
	
	
	
	
	
	/**
	 * Description:系统用户新增
	 * @param req
	 * @param resp
	 * @param user
	 * @author dingjiang
	 * @date 2017年10月19日下午3:10:21
	 */
	@RequiresRoles(UserType.SYSTEM)
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public void register(HttpServletRequest req, HttpServletResponse resp, SystemUserEntity user){
		try {
			//验证非空
			if ( null == user.getUserName() || StringUtils.isEmpty(user.getUserName()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "用户名不能为空");
				return ;
			}
			if ( null == user.getPassword() || StringUtils.isEmpty(user.getPassword()) ) 
				user.setPassword("123456");
			//用户名判重
			boolean flag = systemUserService.verifyUniquely(user.getUserName());
			if (flag) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "重复的用户名");
				return;
			}
			boolean result = systemUserService.register(user);
			doResult(resp, result, result ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, 
					getCurrentSystemUser().getUserName(), result ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value= "/selectpage", method = RequestMethod.POST)
	@ResponseBody
	public void selectPage(HttpServletRequest req, HttpServletResponse resp,
			Integer page, Integer rows, String order, String sort){
		try {
			if (page == null) page = 1;
			if (rows == null) rows = 10;
			PageUtils<SystemUserVo> pageinfo = new PageUtils<>(page, rows, sort, order);
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
}
